<template>
  <div>
    <div v-if="row.actions.length > 2">
      <a
        v-if="showBtn(row.actions[0].label)"
        @click="handleClickMore(row.actions[0].name, row)"
        >{{ row.actions ? row.actions[0].label : "" }}</a
      >
      <Divider type="vertical" />
      <Dropdown @on-click="(name) => handleClickMore(name, row)" transfer>
        <a
          >更多
          <Icon type="ios-arrow-down" />
        </a>
        <DropdownMenu slot="list">
          <template v-for="(item, i) in row.actions.slice(1)">
            <DropdownItem :key="i" :name="item.name" v-if="showBtn(item.label)"
              >{{ item.label }}
            </DropdownItem>
          </template>
        </DropdownMenu>
      </Dropdown>
    </div>
    <div v-else>
      <a
        v-if="row.actions && showBtn(row.actions[0].label)"
        @click="handleClickMore(row.actions[0].name, row)"
        >{{ row.actions[0].label }}</a
      >
      <Divider v-if="row.actions && row.actions.length > 1" type="vertical" />
      <a
        v-if="
          row.actions && row.actions.length > 1 && showBtn(row.actions[1].label)
        "
        @click="handleClickMore(row.actions[1].name, row)"
        >{{ row.actions[1].label }}</a
      >
    </div>
    <Modal v-model="auditModal" title="归类审核">
      <Form ref="formValidate" :model="formData" :label-width="0">
        <FormItem label="" prop="">
          <Input
            v-model="formData.note"
            type="textarea"
            :autosize="{ minRows: 2, maxRows: 5 }"
            placeholder="请输入审核批注"
          ></Input>
        </FormItem>
      </Form>
      <div slot="footer">
        <Button
          type="primary"
          :loading="aloading"
          @click.stop="auditSubit('1')"
        >
          <span v-if="!aloading">通过</span>
          <span v-else>Loading...</span>
        </Button>
        <Button
          type="primary"
          :loading="aloading"
          @click.stop="auditSubit('0')"
        >
          <span v-if="!aloading">拒绝</span>
          <span v-else>Loading...</span>
        </Button>
      </div>
    </Modal>
    <!-- 分页 end  -->
    <Modal
      v-model="showProp"
      title="关联分类"
      width="800"
      :fullscreen="true"
      @on-visible-change="visibleChange"
    >
      <Card title="已关联分类">
        <Row
          type="flex"
          class="height30"
          v-for="(item, index) in seletDataList"
          :key="index"
        >
          <Col>{{ item.fullNames }}</Col>
          <div @click="clickDel(item.uuid)">
            <Col>
              <Icon color="red" type="md-close" />
            </Col>
          </div>
        </Row>
      </Card>
      <Card>
        <div>
          <Row type="flex" style="width: 400px">
            <Input
              search
              enter-button
              placeholder=""
              style="width: 250px"
              v-model="searchKey"
              @on-search="inputSub"
            />
            <Button style="margin-left: 8px" @click="reSetSelect">重置</Button>
          </Row>
          <div>
            <Row style="margin-top: 20px" v-if="isSearch">搜索结果：</Row>
            <div v-if="isSearch && inputValue && inputValue.length > 0">
              <Row
                v-for="(item, index) in inputValue"
                :key="index"
                type="flex"
                class="height30"
              >
                <Col>{{ item.fullNames }}</Col>
                <Col style="margin-left: 10px"
                  ><Button type="primary" @click="searchRelation(item)"
                    >关联</Button
                  ></Col
                >
              </Row>
            </div>
            <Row v-if="isSearch && inputValue.length == 0">暂无搜索结果</Row>
            <Spin size="large" fix v-if="spinShow"></Spin>
          </div>
        </div>
        <Tree
          ref="tree"
          :data="rootDate"
          :load-data="loadData"
          @on-check-change="treeCheckChange"
          show-checkbox
          check-strictly
        />
      </Card>
      <div slot="footer">
        <Button @click="createRelate('2')">取消</Button>
        <Button type="primary" @click="createRelate('1')">确定</Button>
      </div>
    </Modal>
  </div>
</template>
<script>
import dynamictableactions from '@/mixins/dynamictableactions'; // 混入通用代码
import { ApiRequest } from '@api/basePage';
import { mapGetters } from 'vuex';
import { getBtnsId } from '@/libs/btnsPermission';
export default {
  mixins: [dynamictableactions],
  data () {
    return {
      actions: [],
      auditModal: false,
      formData: {
        type: [],
        object: []
      },
      aloading: false,
      showProp: false,
      rootDate: [],
      uuid: '', // 当前选中的uuid
      checkData: [],
      seletDataList: [],
      inputValue: [],
      isSearch: false,
      spinShow: false,
      searchKey: ''
    };
  },
  computed: {
    ...mapGetters('permissions/systemBtns', ['showBtn'])
  },
  methods: {
    reSetSelect () {
      this.initData();
    },
    initData () {
      let data = {
        parentUuid: 'systemUuid'
      };
      // 获取份额里
      ApiRequest(
        this.requestApi.getPlatCategorySubByParentUuid.url,
        this.requestApi.getPlatCategorySubByParentUuid.type,
        data,
        true
      ).then(res => {
        if (res.retStatus === '1') {
          let myNewData = [];
          res.retData.forEach(item => {
            myNewData.push({
              title: item.categoryName,
              uuid: item.uuid,
              levelNum: item.levelNum,
              loading: false,
              disableCheckbox: true,
              disabled: true,
              children: []
            });
          });
          this.rootDate = myNewData;
        }
      });
    },
    // 获取已关联的数据
    initTopData () {
      this.seletDataList = [];
      let data = {
        classficationUuid: this.uuid
      };
      ApiRequest(
        this.requestApi.getCateUuidsByClassficationUuid.url,
        this.requestApi.getCateUuidsByClassficationUuid.type,
        data,
        true
      ).then(res => {
        if (res.retStatus === '1' && res.retData !== null) {
          res.retData.forEach(element => {
            if (element.levelNum === '4') {
              this.seletDataList.push(element);
            }
          });
        } else {
          this.seletDataList = [];
        }
      });
    },
    loadData (item, callback) {
      this._loadData(item.uuid, callback);
    },
    _loadData (code, callback) {
      let data = {
        parentUuid: code
      };
      // 创建分类
      ApiRequest(
        this.requestApi.getPlatCategorySubByParentUuid.url,
        this.requestApi.getPlatCategorySubByParentUuid.type,
        data,
        true
      ).then(res => {
        if (res.retStatus === '1') {
          let myNewData = [];
          let isCheck = false;
          if (res.retData !== null) {
            this.seletDataList.forEach(item => {
              res.retData.forEach(item2 => {
                if (item.uuid === item2.uuid) {
                  isCheck = true;
                } else {
                  isCheck = false;
                }
              });
            });
            // disableCheckbox
            res.retData.forEach(item => {
              myNewData.push({
                title: item.categoryName,
                uuid: item.uuid,
                levelNum: item.levelNum,
                disabled: item.levelNum !== '4',
                disableCheckbox: item.levelNum !== '4',
                loading: false,
                checked: isCheck,
                children: []
              });
            });
            callback(myNewData);
          } else {
            callback(myNewData);
          }
        }
      });
    },
    handleClickMore (name, row) {
      const that = this;
      if (name === 'Delete') {
        this.$Modal.confirm({
          title: '删除操作',
          content: '确定删除此数据吗？',
          onOk: () => {
            let curBtnId = getBtnsId('删除');
            sessionStorage.setItem('buttonId', curBtnId);
            let data = {
              uuids: row.uuid
            };
            // 开始请求商品列表
            ApiRequest(
              this.requestApi.delTableList.url,
              this.requestApi.delTableList.type,
              data,
              true
            ).then(res => {
              if (res.retStatus === '1') {
                that.$Message.success('删除成功');
                that.actionsChange();
              }
            });
          }
        });
      } else {
        let obj = {}; // 动作的对象信息
        row.actions.forEach(item => {
          if (name === item.name) {
            obj = item;
            return false;
          }
        });
        this.setTableRowData(row);
        if (obj.handleType === 'link') {
          if (obj.label == '编辑') {
            let curBtnId = getBtnsId('编辑');
            sessionStorage.setItem('buttonId', curBtnId);
          } else {
            let curBtnId = getBtnsId('删除');
            sessionStorage.setItem('buttonId', curBtnId);
          }
          // 操作类型为链接时，拼接参数跳转
          let jumpPath = this.jumpPath + obj.name;
          this.$router.push({ path: jumpPath, query: { uuid: row.uuid } });
        } else if (obj.handleType === 'prop') {
          let curBtnId = getBtnsId('关联分类');
          sessionStorage.setItem('buttonId', curBtnId);
          // 操作类型为弹窗时 打开弹窗
          this.showProp = true;
          this.uuid = row.uuid;
          this.initData();
          this.initTopData();
        } else if (obj.handleType === 'audit') {
          let curBtnId = getBtnsId('审核');
          sessionStorage.setItem('buttonId', curBtnId);
          this.formData = {
            note: ''
          };
          this.auditModal = true;
        }
      }
    },
    // 审核通过/拒绝
    auditSubit (state) {
      if (state === '0' && this.formData.note === '') {
        this.$Message.error('请填写审核意见');
        return false;
      }
      this.aloading = true;
      let data = {
        note: this.formData.note,
        uuid: this.row.uuid
      };
      if (state === '0') {
        ApiRequest(
          this.requestApi.auditNoPass.url,
          this.requestApi.auditNoPass.type,
          data
        ).then(res => {
          this.aloading = false;
          this.$Message.success('操作成功');
          this.auditModal = false;
          this.actionsChange();
        });
      } else {
        ApiRequest(
          this.requestApi.auditPass.url,
          this.requestApi.auditPass.type,
          data
        ).then(res => {
          this.aloading = false;
          this.$Message.success('操作成功');
          this.auditModal = false;
          this.actionsChange();
        });
      }
    },
    treeCheckChange () {
      let sdata = this.$refs.tree.getCheckedNodes();
      let data = [];
      sdata.forEach(item => {
        data.push(item.uuid);
        this._loadData(item.uuid, res => {});
      });
      this.checkData = data;
    },
    createRelate (type) {
      if (type === '2') {
        this.showProp = false;
      } else {
        if (this.checkData === null) {
          this.$Message.error('尚未勾选分类!');
          return false;
        }
        let data = {
          cateUuids: this.checkData.join(','),
          classficationUuid: this.uuid
        };
        // 创建分类
        ApiRequest(
          this.requestApi.createRelate.url,
          this.requestApi.createRelate.type,
          data,
          true
        ).then(res => {
          if (res.retStatus === '1') {
            this.$Message.success('保存成功');
            this.showProp = false;
            // this.initData();
            // this.initTopData();
          }
        });
      }
    },
    clickDel (uuid) {
      let data = {
        categoryUuid: uuid,
        relUuids: this.uuid
      };
      // 删除已关联分类
      ApiRequest(
        this.requestApi.baseDelete.url,
        this.requestApi.baseDelete.type,
        data,
        true
      ).then(res => {
        if (res.retStatus === '1') {
          this.$Message.success('删除成功');
          this.initData();
          this.initTopData();
        }
      });
    },
    inputSub (value) {
      if (value) {
        this.spinShow = true;
        this.isSearch = true;
        let data = {
          categoryName: value
        };
        ApiRequest(
          '/sysback/category/productplatformcategory/getByCategoryName',
          'post',
          data,
          true
        ).then(res => {
          this.spinShow = false;
          if (res.retStatus == '1') {
            if (res.retData.length > 0) {
              this.inputValue = res.retData;
            } else {
              this.inputValue = [];
            }
          }
        });
      } else {
        this.$Message.error('请输入搜索内容');
      }
    },
    // 模态框显示状态改变时触发
    visibleChange (type) {
      this.inputValue = [];
      this.isSearch = false;
      this.spinShow = false;
      this.searchKey = '';
    },
    // 单个搜索关联分类
    searchRelation (item) {
      this.spinShow = true;
      if (this.uuid && item.categoryUuids[item.categoryUuids.length - 1]) {
        let data = {
          classficationUuid: this.uuid,
          categoryUuid: item.categoryUuids[item.categoryUuids.length - 1]
        };
        ApiRequest(
          this.requestApi.createSingleRelateClassfication.url,
          this.requestApi.createSingleRelateClassfication.type,
          data,
          true
        ).then(res => {
          if (res.retStatus === '1') {
            this.$Message.success('关联成功');
            this.spinShow = false;
            this.initTopData();
          }
        });
      }
    }
  }
};
</script>
